import type { HttpContext } from '@adonisjs/core/http'
import User from '#models/user'
import { md5 } from '#utils/hash'
import vine from '@vinejs/vine'
import Shop from '#models/shop'

export default class AuthController {
  async login({ request, auth, logger }: HttpContext) {
    const authValidator = vine.compile(
      vine.object({
        userName: vine.string(),
        password: vine.string(),
      })
    )

    const { userName, password } = await request.validateUsing(authValidator)

    const user = await User.query().where('userName', userName).firstOrFail()

    if (user.password !== md5(password)) {
      return '账户名或密码不正确'
    }

    const authInfo = await auth.use('jwt').generate(user)

    logger.warn('login:token:登录成功:' + userName)

    return { user, token: authInfo.token }
  }

  async getInfo({ auth }: HttpContext) {
    return await User.findOrFail(auth.user?.id)
  }

  async logout(ctx: HttpContext) {
    const result = ctx.auth.use('jwt').logout()
    ctx.logger.warn('login:token:登录成功:' + ctx.auth.user!.userName)
    return result
  }

  async switchShop(ctx: HttpContext) {
    const shopId = ctx.request.param('shopId')
    const shop = await Shop.findOrFail(shopId)

    if (ctx.auth.user) {
      ctx.auth.user.loginShopId = shop.id
    }
    const result = await ctx.auth.use('jwt').generate(ctx.auth.user!)

    return result
  }
}
